<template>
  <div class="box" :style="style">1</div>
  <div class="plane" v-for="(item, index) in planes" :key="index" :style="item.style"></div>
  <button @click="left">操作Left</button>
  <button @click="right">操作Right</button>
</template>
<script>
import p2 from '../../libs/p2.min.js'
import { mat2d, vec2 } from '../../libs/glmatrix/gl-matrix-min.js'
export default {
  data() {
    return {
      style: {},
      w: 20,
      h: 20
    }
  },
  methods: {
    left() {
      this.box.velocity = [-50, 50]
    },
    right() {
      this.box.velocity = [50, 50]
    },
    positionMat(p) {
      let { w, h } = this
      let m = mat2d.create()
      //mat2d.translate(m, m, [-w / 2, -w / 2])
      mat2d.translate(m, m, [0, 200])
      mat2d.scale(m, m, [1, -1])
      let e = vec2.create()
      vec2.transformMat2d(e, p, m)
      return e
    }
  },
  mounted() {
    let world = new p2.World({
      grivity: [0, -10]
    })

    let box = new p2.Body({
      position: [100, 100],
      velocity: [20, 0],
      mass: 1
      //angle: Math.PI / 4
    })
    let boxShape = new p2.Box({
      width: 20,
      height: 20
    })
    box.addShape(boxShape, [0, 0], Math.PI / 3)
    world.addBody(box)

    let plane = new p2.Body({
      mass: 0,
      position: [0, 0]
    })
    let bottomShape = new p2.Plane()
    plane.addShape(bottomShape)
    let rightShape = new p2.Plane()
    plane.addShape(rightShape, [window.innerWidth, 0], Math.PI / 2)
    let leftShape = new p2.Plane()
    plane.addShape(leftShape, [10, 0], -Math.PI / 2)
    let topShape = new p2.Plane()
    plane.addShape(topShape, [0, 200], Math.PI)
    world.addBody(plane)

    this.planes = [leftShape, rightShape, topShape, bottomShape].map((res) => {
      let angle = res.angle
      let e = this.positionMat(res.position)
      return {
        style: {
          transform: `translate(${e[0]}px,${e[1]}px) rotate(${angle}rad)`
        }
      }
    })

    this.box = box

    const step = () => {
      let { position, angle } = box
      let [boxShape] = box.shapes
      let [x, y] = position
      let { w, h } = this
      let e = this.positionMat(position)

      this.style = {
        transform: `translate(${e[0] - w / 2}px,${e[1] - h / 2}px) rotate(${angle + boxShape.angle}rad)`
      }
      console.log(this.style)
    }

    const animate = () => {
      world.step(1 / 60)
      step()
      requestAnimationFrame(animate)
    }
    animate()
  }
}
</script>
<style type="text/css">
html,
body {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  margin: 0;
  transform-style: preserve-3d;
}
.box {
  width: 20px;
  height: 20px;
  border: 1px solid #000;
  box-sizing: border-box;
  font-size: 12px;
  text-align: center;
  line-height: 20px;
  position: absolute;
  left: 0;
  top: 0;
}
.plane {
  position: absolute;
  width: 200vw;
  height: 1px;
  left: 0;
  top: 0;
  margin-left: -100vw;
  background: #000;
}
</style>
